package top.lshaci.learning.thread;

/**
 * YieldNotReleaseLockTest
 *
 * @author lshaci
 * @since 1.0.0
 */
public class YieldNotReleaseLockTest {

    /**
     * jps
     * jstack $PID
     *
     * "main" #1 prio=5 os_prio=0 tid=0x0000000003452800 nid=0x1a64 waiting on condition [0x0000000002eef000]
     *    java.lang.Thread.State: TIMED_WAITING (sleeping)
     *         at java.lang.Thread.sleep(Native Method)
     *         at top.lshaci.learning.thread.YieldNotReleaseLockTest.main(YieldNotReleaseLockTest.java:27)
     *         - locked <0x000000078096ea78> (a java.lang.Object)
     *
     * "t1 -- " #11 prio=5 os_prio=0 tid=0x000000001c592800 nid=0x33b8 waiting for monitor entry [0x000000001ce4e000]
     *    java.lang.Thread.State: BLOCKED (on object monitor)
     *         at top.lshaci.learning.thread.YieldNotReleaseLockTest.lambda$main$0(YieldNotReleaseLockTest.java:16)
     *         - waiting to lock <0x000000078096ea78> (a java.lang.Object)
     *         at top.lshaci.learning.thread.YieldNotReleaseLockTest$$Lambda$1/381259350.run(Unknown Source)
     *         at java.lang.Thread.run(Thread.java:748)
     *
     * 1、main线程中调用Thread.yield()
     * 2、main线程仍然持有锁：locked 0x000000078096ea78
     * 3、t1  线程仍然在等待锁：waiting to lock 0x000000078096ea78
     */
    public static void main(String[] args) throws Exception {
        final Object lock = new Object();

        Thread t1 = new Thread(() -> {
            synchronized (lock) {
                for (int i = 0; i < 100; i++) {
                    System.out.println("t1 -- " + i);
                }
            }
        }, "t1 -- ");
        t1.start();

        synchronized (lock) {
            for (int i = 0; i < 100; i++) {
                if (i == 20) {
                    Thread.yield();
                    Thread.sleep(5000);
                }
                System.out.println(Thread.currentThread().getName() + " -- " + i);
            }
        }
    }
}
